package org.example.biz.config;

import java.util.Date;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.example.biz.entity.IDable;
import org.example.biz.entity.Updateable;
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertCallback;
import org.springframework.data.mongodb.core.mapping.event.BeforeSaveCallback;
import org.springframework.stereotype.Component;

/**
 * @Title : ConvertUpdate
 * @Description:
 * @author: libo@juzishuke.com
 * @date: 2023/12/15 10:53
 * @Version:1.0
 */
@Slf4j
@Component
public class ConvertUpdate2 implements BeforeSaveCallback, BeforeConvertCallback {

    @Override
    public Object onBeforeSave(Object entity, Document document, String collection) {
        log.info("开始执行了保存操作-------------------------------------");
        return entity;
    }

    @Override
    public Object onBeforeConvert(Object entity, String collection) {
        log.info("开始执行保存前转换回调操作-------------------------------------");
        if (entity instanceof Updateable) {
            Object id = null;
            if (entity instanceof IDable) {
                id = ((IDable) entity).getId();
            }
            Updateable entityGhost = (Updateable) entity;
            if (Objects.isNull(id) && Objects.isNull(entityGhost.getCreateTime())) {
                // 没有id，是插入操作，插入创建时间
                entityGhost.setCreateTime(new Date());
            }
            entityGhost.setUpdateTime(new Date());
        }
        return entity;
    }
}
